import {
  getMultiData, getGoodsData
} from "../../service/home"

const types = ['pop','new','sell'];
const MAX_BACK_TOP = 500;//回到顶部的位置

Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    recommends: [],
    titles:[
      '流行','新款','精选'
    ],
    goods:{
      pop:{
        page:0,
        list:[]
      },
      new:{
        page:0,
        list:[]
      },
      sell:{
        page:0,
        list:[]
      }
    },
    currentType:'pop',
    isShowTop:false,
    isTabFix:false,
    tabScrollTop:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //1. 请求轮播图以及推荐数据
    this._getMultiData();
    this._getGoodsData('pop');
    this._getGoodsData('new');
    this._getGoodsData('sell');
  },

  //_私有函数，获取轮播图和推荐数据
  _getMultiData(){
    getMultiData().then(res => {
      const banners = res.data.data.banner.list;
      const recommends = res.data.data.recommend.list;
      this.setData({
        banners: banners,
        recommends: recommends
      })
    })
  },

  //获取商品数据
  _getGoodsData(type){
    //获取页码
    const page = this.data.goods[type].page+1;
    //发送网络请求
    getGoodsData(type,page).then(res => {
      //取出数据
      const list = res.data.data;
      //设置值到对应的list中
      const oldList = this.data.goods[type].list;
      oldList.push(...list);
      //key值
      const typeKey = `goods.${type}.list`;
      const pageKey = `goods.${type}.page`
      this.setData({
        [typeKey]:oldList,
        [pageKey]:page
      })
    });
  },

  //tab的点击事件
  handleTabClick(event){
    const index = event.detail.index;
    //修改currentType
    this.setData({
      currentType:types[index]
    })
  },

  //到达底部
  onReachBottom(){
    //上拉加载更多
    this._getGoodsData(this.data.currentType)
  },

  //监听页面滚动
  onPageScroll(options){
    const scrollTop = options.scrollTop;
    const flag = scrollTop >= MAX_BACK_TOP;
    if(flag != this.data.isShowTop){
      this.setData({
        isShowTop: flag
      })
    }

    //控制tab的动态显示
    const flag2 = scrollTop >= this.data.tabScrollTop;
    if(flag2 != this.data.isTabFix){
      this.setData({
        isTabFix: flag2
      })
    }
  },

  //监听tab控制的距离，先要监听图片是否加载完成
  hanleImageFinish(){
    wx.createSelectorQuery().select('#tab-control').boundingClientRect(rect => {
      this.data.tabScrollTop = rect.top;
    }).exec();
  }
  

})